package timous.top.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;

@RestController
@RequestMapping("test")
public class TestController {

    @GetMapping("hello")
    public String hello(){
        return "hello";
    }

    public static void main(String[] args) {
        Connection con = null;// 创建一个数据库连接
        PreparedStatement stat = null;// 创建预编译语句的对象
        ResultSet result = null;// 创建一个结果集对象
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
            System.out.println("开始尝试连接数据库！");
            String url = "jdbc:oracle:thin:@clh.timous.top:1521:helowin";//jdbc:oracle:thin:@{ip地址}:{端口号}:{服务名}
            String user = "timous";// 用户名
            String password = "123456";// 密码
            con = DriverManager.getConnection(url, user, password);// 获取连接
            System.out.println("连接成功！");
            String sql = "select * from student";// 预编译语句，“？”代表参数
            stat = con.prepareStatement(sql);// 实例化预编译语句
            //pre.setString(1, "xxx");// 设置参数，前面的1表示参数的索引，而不是表中列名的索引
            result = stat.executeQuery();// 执行查询，注意括号中不需要再加参数
            if (result != null) {
                while (result.next()) {
                    int anInt = result.getInt(1);
                    String string = result.getString(2);
                    System.out.println(string);
                    System.out.println(anInt);
                    //result.getString("xxx") //获取指定字段数据
                    System.out.println("查询到的数据总行数为：" + result.getRow());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();// 异常打印
        } finally {
            try {
                //关闭连接
                if (result != null) result.close();
                if (stat != null) stat.close();
                if (con != null) con.close();
                System.out.println("数据库连接已关闭！");
            } catch (Exception e) {
                e.printStackTrace();// 异常打印
            }
        }
    }

}
